<template>
  <div class="page">
    <global-header @back="$router.back()">
      <template #title>
        <div class="flex justify-center items-center text-[17px] flex-1 w-0">
          <svg-icon class="text-[22px] mr-[5px]" name="icon-service"></svg-icon>
          <span class="truncate">{{ title }}</span>
        </div>
      </template>
    </global-header>
    <main class="page-main">
      <ChatMain ref="chatMainRef" @close="handleShrink" />
    </main>
    <div>
      <ChatFooter ref="chatFooterRef" @scrollToBottom="scrollToBottom" />
    </div>
  </div>
</template>
<route>
  {
    name: "admin-main-chat-room",
    meta: {
      pageIndex: 4,
    }
  }
</route>

<script setup lang="ts">
import ChatMain from "./components/chat-room/main.vue";
import ChatFooter from "./components/chat-room/footer.vue";
import { reqChatKefuList } from "@/api/main";
import { useServiceStore } from "@/store/modules/service";

const route = useRoute();
const chatMainRef = ref();
const chatFooterRef = ref();
const title = computed(() => route.query.name as string);
const userId = computed(() => Number(route.query.uid as string));
const contentId = computed(() => route.query.contentId as string);
const serviceStore = useServiceStore();
const state = reactive<CustomerState>({
  loading: false,
  content: "",
  messages: [],
  autoScrollToBottom: false // 显示滚动到底部
});
provide("state", state);
provide("userId", userId.value);
provide("contentId", contentId.value);

const getData = async () => {
  try {
    state.loading = true;
    const res = await reqChatKefuList({
      Page: 1,
      PageSize: 9999999999,
      UserId: userId.value
    });
    // 清空未读消息
    state.loading = false;
    const list = res.data.List;
    list.reverse();
    state.messages = res.data.List;
    state.autoScrollToBottom = true;
    nextTick(() => {
      chatMainRef.value?.scrollToBottom();
    });
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const scrollToBottom = () => {
  chatMainRef.value?.scrollToBottom();
};

const handleShrink = () => {
  chatFooterRef.value?.shrink();
};

onMounted(() => {
  getData();
  serviceStore.updateServiceCountItem(userId.value, true);
});
</script>
